﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Classes
{
    public class XmlDropDownList : DropDownList
    {
        string xmlPath;
        public string XmlPath { get { return xmlPath; } set { xmlPath = value; } }
        //public override string SelectedValue { get { return base.SelectedValue; } 
        //    set 
        //    {
        //        this.Items[SelectedIndex].Selected = false;
        //        Items.FindByValue(value).Selected = true;
        //    } }

        public XmlDropDownList()
            : base()
        {
            this.Load += new EventHandler(DropDownListFromXml_Load);
        }

        void DropDownListFromXml_Load(object sender, EventArgs e)
        {
            if (xmlPath != "")
            {
                XDocument doc = XDocument.Load(Context.Server.MapPath(xmlPath));
                var q = from d in doc.Descendants("item")
                        select d;
                string val = "";
                string text = "";
                XAttribute valAttr;
                XAttribute textAttr;
                foreach (XElement el in q)
                {
                    valAttr = el.Attribute("value");
                    textAttr = el.Attribute("text");

                    try
                    {
                        text = textAttr.Value;
                        val = valAttr == null ? text : valAttr.Value;
                        this.Items.Add(new ListItem(text, val));
                    }
                    catch { }
                }
            }
        }
    }
}
